package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"short-vid-joy/models/cache"
	"short-vid-joy/models/mysql"
	"short-vid-joy/pkg"

	"short-vid-joy/shortrpc/internal/svc"
	"short-vid-joy/shortrpc/shortrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *shortrpc.RegisterRequest) (*shortrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var findUser mysql.User

	if err := findUser.FindUserByMobile(mysql.DB, in.Mobile); err == nil {
		return nil, errors.New("该手机号已注册，可直接登录")
	}

	user := &mysql.User{
		Mobile:    in.Mobile,
		Password:  pkg.Md5(in.Password),
		HeadImage: "http://t4kafhsbw.hn-bkt.clouddn.com/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.png",
		NickName:  fmt.Sprintf("游客_%d", rand.Intn(9000)+1000),
	}

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()

	if result == "" {
		return nil, errors.New("请发送验证码")
	}

	if in.SmsCode != result {
		return nil, errors.New("验证码错误,请重新输入")
	}

	if err := user.Register(mysql.DB); err != nil {
		return nil, err
	}

	return &shortrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
